package com.instpower.things.instpower;

import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ConnectionManager
 * @Author: hellmash@gmail.com
 * @Date: 2020/3/1
 * @Version: 1.0.0
 * @Description: 连接管理器
 */
public class ConnectionManager {

    private static ConnectionManager mInstance = null;

    private final Map<String, Connection> mConnections;

    private ConnectionManager() {
        mConnections = new ConcurrentHashMap<String, Connection>();
    }

    public static ConnectionManager getInstance() {
        if (mInstance == null) {
            mInstance = new ConnectionManager();
        }
        return mInstance;
    }

    /**
     * 创建一个长连接
     * @param ctx
     * @return
     */
    public Connection create(ChannelHandlerContext ctx) {
        //利用netty4.1的新方法
        String id = ctx.channel().id().asShortText();
        Connection conn = new Connection(id, ctx);
        mConnections.put(id, conn);
        return conn;
    }

    public void remove(String id) {
        Connection conn = mConnections.remove(id);
        if (conn != null) {
            conn.notifyRemoved();
        }
    }

    public void remove(Connection conn) {
        if (conn != null) {
            remove(conn.getId());
        }
    }

    public void remove(ChannelHandlerContext ctx) {
        remove(find(ctx));
    }

    public Connection get(String id) {
        return mConnections.get(id);
    }

    public Connection find(ChannelHandlerContext ctx) {
        return get(ctx.channel().id().asShortText());
    }

    /**
     * mark
     * 不要使用Map里面的size()，每次获取都需要计算
     *
     * @return
     */
    public int count() {
        return mConnections.size();
    }
}
